package com.example.demo.database.services.mysql;


import com.alibaba.druid.pool.DruidDataSource;
import gaarason.database.annotation.Table;
import gaarason.database.connection.GaarasonDataSourceBuilder;
import gaarason.database.contract.connection.GaarasonDataSource;
import gaarason.database.eloquent.Model;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MySqlConnector extends Model<MySqlConnector.Inner, Integer> {
    protected static GaarasonDataSource gaarasonDataSource;

    private static MySqlConnector mySqlConnector = null;


    public static MySqlConnector getInstance() {
        return mySqlConnector;
    }

    private MySqlConnector() {

    }

    public static void build(String url, String username, String password) {
        if (mySqlConnector == null) {
            buildDataSource(url, username, password);
            mySqlConnector = new MySqlConnector();
        }
    }

    private static void buildDataSource(String url, String username, String password) {
        // 设置包扫描配置
        //System.setProperty("gaarason.database.scan.packages", MySqlConnector.class.getName());

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDbType("com.alibaba.druid.pool.DruidDataSource");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setInitialSize(5);
        druidDataSource.setMinIdle(5);
        druidDataSource.setMaxActive(10);
        druidDataSource.setMaxWait(60000);
        // 在此初始化 GaarasonDataSource
        // 结果保存在内静态属性上, 以保证仅初始化一次
        gaarasonDataSource = GaarasonDataSourceBuilder.build(druidDataSource);
    }


    public void runOne(String sql) {
        nativeExecute(sql, null);
    }

    public List<Map<String, Object>> showTable() {
        return nativeQueryList("show tables", new ArrayList<>()).toMapList();
    }

    /**
     * 将`GaarasonDataSource`与`Model`连接起来
     *
     * @return GaarasonDataSource
     */
    @Override
    public GaarasonDataSource getGaarasonDataSource() {
        // 简单的获取已经完成初始化的 GaarasonDataSource
        return gaarasonDataSource;
    }

    /**
     * 定义 entity
     */
    @Data
    @Table
    public static class Inner {
    }
}
